#include "httpserver.hpp"

#define WWWROOT "./wwwroot/"

std::string RequestStr(const HttpRequest& req)
{
    std::string str;
    str += req._method + " " + req._path + " " + req._version + "\r\n";
    for(auto& param : req._params)
    { 
        str += param.first + ": " + param.second + "\r\n";
    }
    for(auto& head : req._headers)
    {
        str += head.first + ": " + head.second + "\r\n";
    }
    str += "\r\n";
    str += req._body;
    return str;
}

void Hello(const HttpRequest& req, HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
    //sleep(15);
}

void Login(const HttpRequest& req, HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

void PutFile(const HttpRequest& req, HttpResponse* rsp)
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}

void DelFile(const HttpRequest& req, HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

int main()
{
    HttpServer server(8050);
    server.SetThreadCount(3);
    std::string base_dir = WWWROOT;
    server.SetBaseDir(base_dir);
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Listen();
    return 0;
}